package gridsoft.sapi.config;

import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.validation.ValidatorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class AppFilter implements Filter { //如果想排除静态资源，可以换成 RouterInterceptor
    static final Logger log = LoggerFactory.getLogger(AppFilter.class);

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);

            if (!ctx.getHandled()) {
                ctx.status(404);
                ctx.render(Result.failure(404, "资源不存在"));
            }
        } catch (ValidatorException e) {
            ctx.status(500);
            ctx.render(Result.failure(e.getMessage()));
        } catch (Throwable e) {
            ctx.status(500);
            log.error("500 ERROR: ", e);
            ctx.render(Result.failure(500, "服务端运行出错", e.getMessage()));
        }
    }
}
